const { logInfo, logWarn, logError } = require('./utils/log.js');

App({
  onLaunch() {
    // 初始化时从本地存储加载到全局变量
    try {
      let wheels = wx.getStorageSync('wheels') || [];
      
      // 加载设置项
      const soundEnabled = wx.getStorageSync('soundEnabled');
      if (soundEnabled !== '') {
        this.globalData.soundEnabled = soundEnabled;
      }
      
      const vibrateEnabled = wx.getStorageSync('vibrateEnabled');
      if (vibrateEnabled !== '') {
        this.globalData.vibrateEnabled = vibrateEnabled;
      }
      
      const spinDuration = wx.getStorageSync('spinDuration');
      if (spinDuration !== '') {
        this.globalData.spinDuration = spinDuration;
      }
      
      // 如果是首次使用（没有任何转盘），自动创建默认转盘
      if (wheels.length === 0) {
        const defaultWheel = {
          id: 'default_breakfast_' + Date.now(),
          name: '午餐吃什么',
          items: [
            { text: '盒饭🍱', color: '#ff7675', weight: 1 },
            { text: '米饭🍚', color: '#74b9ff', weight: 1 },
            { text: '咖喱饭🍛', color: '#55efc4', weight: 1 },
            { text: '面条🍜', color: '#ffeaa7', weight: 1 },
            { text: '意大利面🍝', color: '#a29bfe', weight: 1 },
            { text: '汉堡包🍔', color: '#fd79a8', weight: 1 },
		        { text: '薯条🍟', color: '#fdcb6e', weight: 1 },
            { text: '披萨🍕', color: '#00cec9', weight: 1 },
		        { text: '火锅🍲', color: '#ff7675', weight: 1 },
            { text: '墨西哥卷饼🌮', color: '#74b9ff', weight: 1 },
		        { text: '玉米煎饼🌯', color: '#55efc4', weight: 1 },
            { text: '三明治🥪', color: '#ffeaa7', weight: 1 },
            { text: '寿司🍣', color: '#a29bfe', weight: 1 },
            { text: '炸虾🍤', color: '#fd79a8', weight: 1 },
		        { text: '沙拉🥗', color: '#fdcb6e', weight: 1 }
          ]
        };
        
        wheels.push(defaultWheel);
        wx.setStorageSync('wheels', wheels);
        logInfo('为首次用户创建默认转盘：午餐吃什么');
      }
      
      this.globalData.allWheels = wheels;
    } catch (e) {
      logError('初始化全局allWheels失败', e);
    }
    
    // 检查每日登录奖励
    this.checkDailyLogin();
  },

  // 检查每日登录奖励
  checkDailyLogin() {
    try {
      const today = this.getToday();
      const lastLoginDate = wx.getStorageSync('lastLoginDate') || '';
      
      if (lastLoginDate !== today) {
        // 今天首次登录
        let consecutiveDays = wx.getStorageSync('consecutiveLoginDays') || 0;
        let expBonus = 1; // 基础奖励
        
        if (this.isConsecutiveDay(lastLoginDate, today)) {
          // 连续登录
          consecutiveDays += 1;
          expBonus = Math.min(consecutiveDays, 7); // 最多+7
        } else {
          // 非连续登录，重置
          consecutiveDays = 1;
          expBonus = 1;
        }
        
        this.addLuckyExp(expBonus);
        wx.setStorageSync('lastLoginDate', today);
        wx.setStorageSync('consecutiveLoginDays', consecutiveDays);
        wx.setStorageSync('hasSpinToday', false); // 重置今日转盘状态
        
        // 重置所有模式的每日状态
        wx.setStorageSync('hasCoinToday', false);
        wx.setStorageSync('hasCardsToday', false);
        wx.setStorageSync('hasMuyuToday', false);
        wx.setStorageSync('hasFortuneToday', false);
        
        // 延迟显示登录奖励提示，避免与其他提示冲突
        setTimeout(() => {
          wx.showToast({
            title: `登录奖励+${expBonus}经验`,
            icon: 'success',
            duration: 1000
          });
        }, 800);
      }
    } catch (e) {
      logError('检查每日登录奖励失败', e);
    }
  },

  // 增加幸运经验
  addLuckyExp(exp) {
    let luckyLevel = wx.getStorageSync('luckyLevel') || 0;
    let luckyExp = wx.getStorageSync('luckyExp') || 0;
    const levelExpRequirements = [10, 50, 100, 500, 1000, 2000, 5000, 10000]; // LV0-LV7升级所需经验
    
    luckyExp += exp;
    
    // 检查是否升级
    while (luckyLevel < 8 && luckyExp >= levelExpRequirements[luckyLevel]) {
      luckyExp -= levelExpRequirements[luckyLevel];
      luckyLevel += 1;
      wx.showToast({
        title: `恭喜升级到LV${luckyLevel}!`,
        icon: 'success',
        duration: 1000
      });
    }
    
    wx.setStorageSync('luckyLevel', luckyLevel);
    wx.setStorageSync('luckyExp', luckyExp);
  },

  // 获取今天日期字符串
  getToday() {
    const now = new Date();
    return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}`;
  },

  // 判断是否连续登录
  isConsecutiveDay(lastDate, currentDate) {
    if (!lastDate) return false;
    
    const last = new Date(lastDate);
    const current = new Date(currentDate);
    const diffTime = current.getTime() - last.getTime();
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
    
    return diffDays === 1;
  },

  globalData: {
    userInfo: null,
    systemInfo: null,
    currentWheel: null,    // 当前选中的转盘
    spinDuration: 3,       // 默认旋转时长3秒
    vibrateEnabled: true, // 全局振动开关状态（默认开启）
    soundEnabled: true,    // 默认开启声音
    // 模式切换相关
    targetMode: undefined,     // 目标模式索引（用于从个人中心跳转）
    targetModeName: undefined, // 目标模式名称（用于显示提示）
    // 热门转盘列表，第一个为"午餐吃什么"
    hotWheels: [
      {
        id: 'lunch',
        name: '午餐吃什么',
        items: [
          { text: '盒饭🍱', color: '#ff7675', weight: 1 },
          { text: '米饭🍚', color: '#74b9ff', weight: 1 },
          { text: '咖喱饭🍛', color: '#55efc4', weight: 1 },
          { text: '面条🍜', color: '#ffeaa7', weight: 1 },
          { text: '意大利面🍝', color: '#a29bfe', weight: 1 },
          { text: '汉堡包🍔', color: '#fd79a8', weight: 1 },
          { text: '薯条🍟', color: '#fdcb6e', weight: 1 },
          { text: '披萨🍕', color: '#00cec9', weight: 1 },
          { text: '火锅🍲', color: '#ff7675', weight: 1 },
          { text: '墨西哥卷饼🌮', color: '#74b9ff', weight: 1 },
          { text: '玉米煎饼🌯', color: '#55efc4', weight: 1 },
          { text: '三明治🥪', color: '#ffeaa7', weight: 1 },
          { text: '寿司🍣', color: '#a29bfe', weight: 1 },
          { text: '炸虾🍤', color: '#fd79a8', weight: 1 },
          { text: '沙拉🥗', color: '#fdcb6e', weight: 1 }
        ]
      }
    ],
    allWheels: [] // 所有可用转盘
  }
});